package com.syx.friend.Service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.syx.api.Model.DTO.JudgeSubmitDTO;
import com.syx.api.Model.RemoteJudgeService;
import com.syx.api.Model.UserExeResult;
import com.syx.api.Model.VO.UserQuestionResultVO;
import com.syx.commoncore.Constant.Constant;
import com.syx.commoncore.Constant.QuestionResType;
import com.syx.commoncore.Model.Result;
import com.syx.commoncore.Utils.ThreadLocalUtil;
import com.syx.commoncore.enums.ProgramType;
import com.syx.commoncore.enums.Resultcode;
import com.syx.friend.ElasticSearch.QuestionRepository;
import com.syx.friend.Mapper.QuestionMapper;
import com.syx.friend.Mapper.UserSubmitMapper;
import com.syx.friend.Model.question.Question;
import com.syx.friend.Model.question.QuestionCase;
import com.syx.friend.Model.question.es.QuestionES;
import com.syx.friend.Model.user.DTO.UserSubmitDTO;
import com.syx.friend.Model.user.UserSubmit;
import com.syx.friend.Rabbit.JudgeProducer;
import com.syx.friend.Service.IUserQuestionService;
import com.syx.security.Exception.ServiceException;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IUserQuestionServiceImpl implements IUserQuestionService {
    @Resource
    QuestionRepository questionRepository;

    @Resource
    QuestionMapper questionMapper;


    @Resource
    RemoteJudgeService remoteJudgeService;

    @Autowired
    JudgeProducer judgeProducer;

    @Resource
    UserSubmitMapper userSubmitMapper;




    @Override
    public Result<UserQuestionResultVO> submit(UserSubmitDTO userSubmitDTO) {
        //提交题目id问题id，题目代码java

        if (ProgramType.JAVA.getValue().equals(userSubmitDTO.getProgramType())){
            JudgeSubmitDTO judgeSubmitDTO=assembleJudgeSubmitDTO(userSubmitDTO);
            return remoteJudgeService.doJudgeJavaCode(judgeSubmitDTO);

        }
        throw new ServiceException(Resultcode.FAILED_SUPPORT_PROGRAM);

    }

    @Override
    public boolean rabbitSubmit(UserSubmitDTO userSubmitDTO) {
        if (ProgramType.JAVA.getValue().equals(userSubmitDTO.getProgramType())){
            JudgeSubmitDTO judgeSubmitDTO=assembleJudgeSubmitDTO(userSubmitDTO);
            judgeProducer.produceMsg(judgeSubmitDTO);
            return true;

        }
        throw new ServiceException(Resultcode.FAILED_SUPPORT_PROGRAM);
    }

    @Override
    public Result<UserQuestionResultVO> exeResult(Long examId, Long questionId, String currentTime) {
        Long userId = ThreadLocalUtil.get(Constant.USER_ID, Long.class);
        UserSubmit userSubmit=userSubmitMapper.selectCurrentUserSubmit(userId,examId,questionId,currentTime);
        //判题还没有结束
        UserQuestionResultVO userQuestionResultVO=new UserQuestionResultVO();

        if (userSubmit==null){
            //正在判题
            userQuestionResultVO.setPass(QuestionResType.IN_JUDGE.getValue());

        }else {
            userQuestionResultVO.setPass(userSubmit.getPass());
            userQuestionResultVO.setExeMessage(userSubmit.getExeMessage());
            if (StrUtil.isNotEmpty(userSubmit.getCaseJudgeRes())) {
                userQuestionResultVO.setUserExeResultList(JSON.parseArray(userSubmit.getCaseJudgeRes(), UserExeResult.class));
            }
        }


        return Result.success(userQuestionResultVO);









    }


    //封装judge
    private JudgeSubmitDTO assembleJudgeSubmitDTO(UserSubmitDTO userSubmitDTO) {
        Long questionId=userSubmitDTO.getQuestionId();
        //通过questionId查找对应的questionES
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        JudgeSubmitDTO judgeSubmitDTO=new JudgeSubmitDTO();
        if (questionES!=null){
            //先从es中查，没查到再去数据库查
            BeanUtil.copyProperties(questionES,judgeSubmitDTO);


        }else {
            //es中没有就从数据库中查，并且放到es和questiones中
            Question question = questionMapper.selectById(questionId);
            BeanUtil.copyProperties(question,judgeSubmitDTO);
            QuestionES refreshQuestionES=new QuestionES();
            BeanUtil.copyProperties(question,refreshQuestionES);
            questionRepository.save(refreshQuestionES);


        }
        judgeSubmitDTO.setUserId(ThreadLocalUtil.get(Constant.USER_ID,Long.class));
        judgeSubmitDTO.setExamId(userSubmitDTO.getExamId());
        judgeSubmitDTO.setProgramType(ProgramType.JAVA.getValue());
        judgeSubmitDTO.setUserCode(codeConnect(userSubmitDTO.getUserCode(), questionES.getMainFuc()));
        List<QuestionCase> questionCaseList =  JSONUtil.toList(questionES.getQuestionCase(), QuestionCase.class);
        List<String> input = questionCaseList.stream().map(QuestionCase::getInput).toList();
        judgeSubmitDTO.setInputList(input);
        List<String> output = questionCaseList.stream().map(QuestionCase::getOutput).toList();
        judgeSubmitDTO.setOutputList(output);
        return judgeSubmitDTO;



    }
    //拼接代码
    private String codeConnect(String userCode, String mainFuc) {
        String targetCharacter = "}";
        int targetLastIndex = userCode.lastIndexOf(targetCharacter);
        if (targetLastIndex != -1) {
            return userCode.substring(0, targetLastIndex) + "\n" + mainFuc + "\n" + userCode.substring(targetLastIndex);
        }
        throw new ServiceException(Resultcode.FAILED);
    }
}
